package games.flvPlayer.control
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class ProgressControl extends EventDispatcher
	{
		private var m_ui:Sprite;
		private var m_bar:*;
		private var m_prog:*;
		
		private var m_showProg:*;
		
		private var m_value:Number;
		private var m_select:Boolean;
		
		public function ProgressControl(mc:Sprite)
		{
			m_ui = mc;
			init();
		}
		
		public function destroy():void
		{
			m_bar.removeEventListener(MouseEvent.MOUSE_DOWN,onStartDrag);			
			m_prog.addEventListener(MouseEvent.CLICK,onClickProg);
		}
		
		public function get value():Number
		{
			var per:int = Math.ceil((m_bar.x )/ (m_prog.width - m_bar.width) * 100);
			if(per < 0)per = 0;
			if(per > 100) per = 100;
			return per;
		}
		
		public function set value(n:Number):void
		{
			if(m_select)return;
			m_value = n;
			showProg();
		}
		
		private function init():void
		{
			m_bar = m_ui.getChildByName("mcPointer");
			m_prog = m_ui.getChildByName("bg");
			m_showProg = m_ui.getChildByName("mcPlayBar");
			
			m_ui["mcLoadBar"].mouseEnabled = m_ui["mcLoadBar"].mouseChildren = false;
			m_ui["mcPlayBar"].mouseEnabled = m_ui["mcPlayBar"].mouseChildren = false;
			
			m_bar.mouseChildren = false;
			m_prog.mouseChildren = false;
			m_bar.buttonMode = true;
			m_prog.buttonMode = true;
			
			m_bar.addEventListener(MouseEvent.MOUSE_DOWN,onStartDrag);			
			m_prog.addEventListener(MouseEvent.CLICK,onClickProg);
		}
		
		private function onStartDrag(e:MouseEvent):void
		{
			m_bar.startDrag(false,new Rectangle(0,0,m_prog.width-m_bar.width ,0));
			m_select = true;
			m_bar.stage.addEventListener(MouseEvent.MOUSE_MOVE,onChange);
			m_bar.stage.addEventListener(MouseEvent.MOUSE_UP,onStopDrag);
		}
		
		private function onStopDrag(e:MouseEvent):void
		{
			m_bar.stopDrag();
			m_select = false;
			m_bar.stage.removeEventListener(MouseEvent.MOUSE_MOVE,onChange);
			m_bar.stage.removeEventListener(MouseEvent.MOUSE_UP,onStopDrag);
		}
		
		private function onClickProg(e:MouseEvent):void
		{
			m_bar.x = m_prog.mouseX;
			update();
		}
		
		private function onChange(e:MouseEvent):void
		{
			update();
		}
		
		private function update():void
		{
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		private function showProg():void
		{
			m_bar.x = m_value * (m_prog.width - m_bar.width);
			m_showProg.scaleX = m_value;
		}
	}
}